from django.http import JsonResponse
from django.contrib.auth import logout
import hashlib
import datetime
import math
import pymysql
from zentao.settings import PYMYSQL_CONF

from apps.homepage.models import ZtUser
from apps.utils.aes import MyAES

import time
from functools import wraps

def timing_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"Function {func.__name__!r} executed in {(end_time - start_time)*1000:.2f}ms")
        return result
    return wrapper

#判断是否登录
def has_permission(request):

    # session没有token，则未登录
    session_token = request.session.get('token')
    if not session_token:
        return False

    # 如果未传入token，则未登录
    request_token = request.META.get('HTTP_TOKEN')
    if not request_token:
        return False

    #如果都传入，则比对是否一致
    if session_token == request_token:
        return True
    else:
        return False

#登录
@timing_decorator
def login_view(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        #未填写账号或密码
        if not username or not password:
            res = {
                'code': 0,
                'msg': '未填写用户名或密码'
            }
            return JsonResponse(res)
        # print(username, password)

        # 对密码进行MD5加密
        encrypted_password = hashlib.md5(password.encode()).hexdigest()

        # 验证用户
        try:
            user = ZtUser.objects.filter(account=username, deleted='0').select_related('dept').first()
            if user:

                #判断密码是否正确
                if encrypted_password != user.password:
                    res = {
                        'code': 0,
                        'msg': "密码错误"
                    }
                    return JsonResponse(res)

                #加密token
                # aes，id、account
                token = MyAES().encrypted(str(user.id)+str(user.account))
                # 登录用户，创建session
                request.session['token'] = token
                request.session['account'] = username
                request.session['dept'] = user.dept.name if user.dept else ''

                #插入登录动作日志
                # 在zt_action中标识是谁插入的
                # SQL 插入语句
                sql = "INSERT INTO `zt_action` " \
                      "(`objectType`, `objectID`, `product`, `project`, `execution`, `actor`, `action`,`date`," \
                      "`comment`,`extra`,`read`,`vision`,`efforted`)" \
                      " VALUES " \
                      "(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
                # 要插入的数据
                current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                values = (
                    'user', 0, f',0,', 0, 0, username, 'login', current_time,
                    '', '', '0', 'rnd', 0)
                # 连接数据库
                # pymysql连接数据
                connection = pymysql.connect(**PYMYSQL_CONF)
                with connection.cursor() as cursor:

                    # 执行 SQL 语句
                    cursor.execute(sql, values)

                    # 提交事务
                    connection.commit()
                connection

                res = {
                    'code': 1,
                    'msg': "登陆成功",
                    "token": token
                }
                return JsonResponse(res)
            else:
                res = {
                    'code': 0,
                    'msg': "没有该用户"
                }
                return JsonResponse(res)

        except ZtUser.DoesNotExist:
            res = {
                'code': 0,
                'msg': "用户名或密码错误"
            }
            return JsonResponse(res)

    #不是post请求
    res = {
        'code': 0,
        'msg': "不支持的请求方法"
    }
    return JsonResponse(res, status=405)

#获取用户信息
@timing_decorator
def get_user_info(request):
    if request.method == 'GET':

        # 检查用户是否登录
        if not has_permission(request):
            # 如果用户未登录，抛出 AuthenticationFailed 异常
            return JsonResponse({'code': 0, 'msg': '未登录'})
        # print(request.session)
        # if 'token' in request.session:
        #     del request.session['token']
        account = request.session['account']
        user = ZtUser.objects.get(account=account, deleted='0')

        #时间转换
        if user.join:
            # 将datetime.date对象转换为datetime.datetime对象，时间为午夜
            datetime_object = datetime.datetime.combine(user.join, datetime.time.min)
            join = math.ceil(datetime_object.timestamp())
        else:
            join = math.ceil(datetime.datetime.now().timestamp())

        res = {
            'code': 1,
            'msg': "获取成功",
            'data':{
                'id': user.id,
                'name': user.realname,
                'username': account,
                'status': 1,
                'telephone': user.mobile,
                'createTime': join,
                'deleted': 0
            }
        }

        return JsonResponse(res)
    else:
        res = {
            'code': 0,
            'msg': "不支持的请求方法"
        }
        return JsonResponse(res, status=405)

#注销
@timing_decorator
def logout_view(request):
    if request.method == 'POST':
        # print(request.session)
        # if 'token' in request.session:
        #     del request.session['token']
        logout(request)
        res = {
            'code': 1,
            'msg': "注销成功"
        }
        return JsonResponse(res)
    else:
        res = {
            'code': 0,
            'msg': "不支持的请求方法"
        }
        return JsonResponse(res, status=405)